/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.tarena.lbs.attach.rpc;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.tarena.lbs.attach.api.AttachApi;
import com.tarena.lbs.attach.dao.mapper.AttachMapper;
import com.tarena.lbs.attach.pojo.dto.AttachDTO;
import com.tarena.lbs.attach.pojo.dto.AttachQrDTO;
import com.tarena.lbs.attach.pojo.param.AttachQRParam;
import com.tarena.lbs.attach.pojo.param.PicUpdateParam;
import com.tarena.lbs.attach.pojo.query.AttachQuery;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;


@DubboService
@Slf4j
public  class AttachRpcService implements AttachApi {
    @Autowired
    private AttachMapper attachMapper;

    private static final int BACKGROUND_COLOR = 0xFFFFFFFF;
    private static final int FRONT_COLOR = 0xFF000000;
    private static final int CODE_WIDTH = 180;
    private static final int CODE_HEIGHT = 180;

    @Override
    public List<AttachDTO> getAttachInfo(AttachQuery attachQuery) {
        return Collections.emptyList();
    }

    @Override
    public boolean batchUpdateBusiness(List<PicUpdateParam> picParams) {
        return false;
    }

    @Override
    public AttachQrDTO generateQrCode(AttachQRParam attachQRParam) throws WriterException, IOException {
        // 生成二维码图片
        BufferedImage bufferedImage = getBufferedImage(attachQRParam.getContent());

        // 生成唯一文件名
        UUID uuid = UUID.randomUUID();

        // 创建日期目录
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String datePath = sdf.format(new Date());

        // 设置存储目录
        String dirPath = "E:/files/"; // 注意：结尾加斜杠
        File dirFile = new File(dirPath + datePath);

        // 确保目录存在
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        // 构建完整文件路径（注意路径分隔符）
        String fileName = uuid + ".png";
        String filePath = dirPath + datePath + "/" + fileName; // 添加斜杠分隔

        // 创建文件对象并保存
        File outputFile = new File(filePath);
        ImageIO.write(bufferedImage, "png", outputFile);

        // 返回文件信息
        AttachQrDTO dto = new AttachQrDTO();
        dto.setUrl(filePath); // 绝对路径
        dto.setFileUuid(fileName); // 相对路径
        dto.setCouponCode(attachQRParam.getCouponCode());
        log.debug("getCouponCode:{}", attachQRParam.getCouponCode());
        return dto;
    }

    @Override
    public AttachQrDTO generateQrCode(String x) throws WriterException, IOException {
        BufferedImage bufferedImage = getBufferedImage(x);

        // 生成唯一文件名
        UUID uuid = UUID.randomUUID();

        // 创建日期目录
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String datePath = sdf.format(new Date());

        // 设置存储目录
        String dirPath = "E:/files/"; // 注意：结尾加斜杠
        File dirFile = new File(dirPath + datePath);

        // 确保目录存在
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        // 构建完整文件路径（注意路径分隔符）
        String fileName = uuid + ".png";
        String filePath = dirPath + datePath + "/" + fileName; // 添加斜杠分隔

        // 创建文件对象并保存
        File outputFile = new File(filePath);
        ImageIO.write(bufferedImage, "png", outputFile);

        // 返回文件信息
        AttachQrDTO dto = new AttachQrDTO();
        dto.setUrl(filePath); // 绝对路径
        dto.setFileUuid(fileName); // 相对路径
        return dto;
    }

    private static BufferedImage getBufferedImage(String content) throws WriterException {

        //com.google.zxing.EncodeHintType：编码提示类型,枚举类型
        Map<EncodeHintType, Object> hints = new HashMap();

        //EncodeHintType.CHARACTER_SET：设置字符编码类型
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        //EncodeHintType.ERROR_CORRECTION：设置误差校正
        //ErrorCorrectionLevel：误差校正等级，L = ~7% correction、M = ~15% correction、Q = ~25% correction、H = ~30% correction
        //不设置时，默认为 L 等级，等级不一样，生成的图案不同，但扫描的结果是一样的
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);

        //EncodeHintType.MARGIN：设置二维码边距，单位像素，值越小，二维码距离四周越近
        hints.put(EncodeHintType.MARGIN, 1);

        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, CODE_WIDTH, CODE_HEIGHT, hints);
        BufferedImage bufferedImage = new BufferedImage(CODE_WIDTH, CODE_HEIGHT, BufferedImage.TYPE_INT_BGR);
        for (int x = 0; x < CODE_WIDTH; x++) {
            for (int y = 0; y < CODE_HEIGHT; y++) {
                bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? FRONT_COLOR : BACKGROUND_COLOR);
            }
        }
        return bufferedImage;
    }

}
